<!--预答辩成绩录入及查询-->
<template>
    <div class="con">
        <inner-breadcrumb v-model="pathKey" :path="path"></inner-breadcrumb>
        <div v-show="pathKey==='main'">
            <ConditionCard v-if="btnIsShow" shadow="never" body-style="padding: 24px 24px 6px 24px;" @search="onSubmit" @reset="reset('queryForm')">
                <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="120px" label-suffix="：">
                  <el-row :gutter="24">
                    <el-col :span="8">
                      <el-form-item :label="$t('label.schoolTerm')">
                        <CalendarSelect v-model="queryForm.yearTerm" @load-done="loadDone" :all="true"></CalendarSelect>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="$t('label.grade')">
                        <el-date-picker v-model="queryForm.grade" value-format="yyyy" type="year" :clearable="true"
                                        :placeholder="$t('paperBlindTrial.gredeTips')" style="width: 100%"/>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.college')">
                          <el-select
                            v-model="queryForm.academyId"
                            style="width: 100%;"
                            clearable
                            filterable
                            :placeholder="$t('common.text.all')"
                            v-clearreadonly
                          >
                            <el-option
                                v-for="item in options.academyId"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                          </el-select>
                        </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item :label="$t('label.major')">
                            <MyMajor :faculty="queryForm.academyId" :filterable="true" :grade="queryForm.grade" v-model="queryForm.majorId" :clearable="true" v-clearreadonly> </MyMajor>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.trainingLevel')" prop="eduLevel">
                            <DictSelect v-model="queryForm.eduLevel" :data="options.eduLevel" :clearable="true"></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.trainingCategory')" prop="eduMode">
                            <DictSelect v-model="queryForm.eduMode" :filterable="true" :data="options.eduMode" :clearable="true"></DictSelect>
                        </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item :label="$t('label.degreeCategory')" prop="degreeType">
                            <DictSelect v-model="queryForm.degreeType" :data="options.degreeType" :clearable="true"></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('label.formLearning')" prop="studyForm">
                            <DictSelect v-model="queryForm.studyForm" :data="options.studyForm" :clearable="true"></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('achievementApply.teacherName')">
                          <el-select
                            v-model="queryForm.stuTutorNo"
                            :remote-method="selectUser"
                            :placeholder="$t('preDefense.teacherNameTips')"
                            filterable
                            remote
                            clearable
                            style="width: 100%;"
                            v-clearreadonly
                          >
                            <el-option
                              v-for="item in users"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            />
                          </el-select>
                        </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item :label="$t('preDefense.grades')">
                            <DictSelect v-model="queryForm.examResult" :data="options.examResult" :clearable="true"></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('preDefense.preDefenseTime')">
                          <el-date-picker
                            :clearable="true"
                            v-model="queryForm.defenseDate"
                            type="daterange"
                            range-separator="~"
                            :start-placeholder="$t('message.startDate')"
                            :end-placeholder="$t('message.endDate')"
                            style="width:100%;">
                          </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="$t('preDefense.defenseAddr')">
                        <el-input v-model="queryForm.defenseAddr" :placeholder="$t('inputPlaceholder')" :clearable="true"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
            </ConditionCard>
            <el-card shadow="never" body-style="padding: 24px;">
              <h1 class="condition-title">{{$t('preDefense.preDefenseLookTitle')}}</h1>
              <div class="edu-opertion-bar">
                  <div class="float-left">
                    <KeywordInput v-model="queryForm.stuNoOrName" :placeholder="$t('achievementApply.tableIplaceholder')" @enter="onSubmit"></KeywordInput>
                  </div>
                <div class="float-right">
                  <el-button type="primary" @click="exportData">{{$t('message.export')}}</el-button>
                </div>
              </div>
              <edu-table ref="tables" :url="tableApi" @load-done="tableLoadDone" :orderFixed="true">
                <el-table-column :min-width="item.width" v-for="item in label" :key="item.props" :label="item.label"
                                 :prop="item.props" :fixed="item.fixed" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <lable v-if="item.props == 'defenseDate'">{{getFormatTime(scope.row[item.props])}}</lable>
                      <lable v-else> {{ scope.row[item.props] }} </lable>
                    </template>
                </el-table-column>
                <el-table-column :min-width="100" :label="$t('preDefense.examResult')" prop="examResult"
                                 show-overflow-tooltip fixed="right">
                  <template slot-scope="scope">
                    <el-select v-if="!scope.row.hideState &&　(global.isAcdemicDean || global.isAdmin)" :key="scope.row.id"
                               v-model="scope.row.examResult" placeholder="">
                      <el-option v-for="selectKey in options.examResult" :key="selectKey.value" :label="selectKey.label"
                                 :value="selectKey.value"></el-option>
                    </el-select>
                    <label v-else>{{fieldChange(options.examResult, scope.row.examResult)}}</label>
                  </template>
                </el-table-column>
                <el-table-column width="130px" :label="$t('nonPublicCourseOpen.operation')" fixed="right">
                  <template slot-scope="scope">
                          <div class="con_btns" @click.stop="">
                            <el-button type="text" v-if="!scope.row.hideState  &&　(global.isAcdemicDean || global.isAdmin)" @click="insertScoreFunc(scope.row)">{{$t('preDefense.resultsRelease')}}</el-button>
                            <el-button type="text" @click="open('preDefenseLookDetails', scope.row)">{{$t('message.detail')}}</el-button>
                            <!-- 导出word_结果表 -->
                            <el-button type="text" v-if="scope.row.examResult" @click="exportWord(scope.row)">{{$t('message.export')}}</el-button>
                          </div>
                      </template>
                  </el-table-column>
              </edu-table>
            </el-card>
        </div>
        <!-- 查看 -->
        <preDefenseLookDetails v-if="pathKey=== 'preDefenseLookDetails'" :options="options" :row="selectRow" @emit:back="backFunc" @emit:click="opens"></preDefenseLookDetails>
    </div>
</template>

<script>
import { applyList, lookExportTable, lookInsertScore, applyTableList, applyExportDoc} from "common/src/api/preDefense";
import MyMajor from "common/src/views/administrator/undergraduateTutor/component/MyMajor";
import commonMixins from 'common/src/views/practiceManagement/commonMixins';
import preDefenseLookDetails from './preDefenseLookDetails';
import { queryDic } from 'common/src/api/dictionary';
import { getSessionUser } from "common/src/api/session";
import { findTeacherInfoList } from 'common/src/api/studentinfo'
import moment from 'moment';
import mixin from 'common/src/mixins/index';
export default {
    components: {
        MyMajor,
        preDefenseLookDetails
    },
    mixins: [commonMixins,mixin],
    props: {},
    data() {
        return {
            tableApi: applyTableList,
            objs: {
                ids: '',
                editFlag: false
            },
            yearTerms: '',
            queryForm: {
              yearTerm: '', // 学年学期
              academyId: '', // 学院
              majorId: '', // 专业
              grade: '', // 年级
              eduLevel: '', // 培养层次
              eduMode: '', // 培养类别
              degreeType: '', // 学位类型
              studyForm: '', // 学习形式
              stuTutorNo: '', // 导师
              examResult: '', // 成绩
              defenseDate: [], // 预答辩时间
              status: 'PASS', //审核状态
              stuNoOrName: ''//学号或姓名模糊查询
            },
            label: [

              {label: this.$t('label.stuCode'), props: 'stuNo', width: 100, fixed: "left"},
              {label: this.$t('label.stuName'), props: 'stuName', width: 90, fixed: "left"},
              {label: this.$t('label.grade'), props: 'grade', width: 60},
              {label: this.$t('label.schoolTerm'), props: 'yearTermI18n', width: 180},
              {label: this.$t('label.college'), props: 'academyName', width: 160},
              {label: this.$t('label.major'), props: 'majorName', width: 160},
              {label: this.$t('label.trainingLevel'), props: 'eduLevelI18n', width: 120},
              {label: this.$t('label.trainingCategory'), props: 'eduModeI18n', width: 150},
              {label: this.$t('label.degreeCategory'), props: 'degreeTypeI18n', width: 150},
              {label: this.$t('label.formLearning'), props: 'studyFormI18n', width: 150},
              {label: this.$t('preDefense.defenseAddr'), props: 'defenseAddr', width: 150},
              {label: this.$t('achievementApply.teacherName'), props: 'stuTutorName', width: 150},
              {label: this.$t('preDefense.preDefenseApplyTime'), props: 'createTime', width: 160},
              {label: this.$t('preDefense.preDefenseTime'), props: 'defenseDate', width: 160},
            ],
            options: {
              majorId: [], // 专业
              academyId: [], // 学院
              examResult: [ // 成绩
                { label: this.$t('message.pass'), value: 'PASS', type: 'success' },
                { label: this.$t('message.noPass'), value: 'UNPASS', type: 'danger' },
              ],
              eduLevel: [], // 培养层次
              eduMode: [], // 培养类别
              degreeType: [], // 学位类型
              studyForm: [], // 学习形式
              direction: [], // 研究方向
            },
            pathKey: 'main',
            path: {
                label: this.$t('preDefense.preDefenseResult'),
                key: 'main',
                disable: false,
                children: [
                    {
                        label: this.$t('achievementApply.checkResult'),
                        key: 'preDefenseLookDetails',
                        disable: true,
                    }

                ]
            },
            selectRow: {},
            btnIsShow: false,
            users: []
        };
    },
    computed: {

    },
    mounted() {
      let param = {
        X_YX: 'academyId', // 学院
        // X_PYCC: 'eduLevel', // 培养层次
        X_PYLB: 'eduMode', // 培养类别
        X_XWLX: 'degreeType', // 学位类型
        K_XXXS: 'studyForm', // 学习形式
        X_YJFX: "direction" // 研究方向
      };
      this.getType();
      this.initOptions(param);
      this.getEdulevel();
      if(this.global.isStudent){
        this.onSubmit();
      }
    },
    methods: {
        //时间格式化
        getFormatTime(val) {
          return moment(val).format('YYYY-MM-DD')
        },
        getEdulevel() { // val: {  X_PYCC: 'trainingLevel',   G_ZY: 'profession'} // 专业
          const data = {
            lang: this.$store.getters.language || 'cn',
            type: 'allChild',
            keys: ['X_PYCC']
          };
          return new Promise((resolve, reject) => {
              queryDic(data).then(res => {
                  if (res.code === 200) {
                    this._fill('eduLevel', res.data['X_PYCC']);
                    this.options.eduLevel = this.options.eduLevel.filter(v => v.value === '4' || v.value === '6');
                  }
                  resolve(this.options);
              }).catch((err) => {
                  reject(err);
              });
          });
        },
        //获取当前登录角色权限信息
        getType() {
          if(this.global.isStudent){
            //学生
            this.btnIsShow = false;
          }else{
            // 非学生放开成绩录入按钮
            this.btnIsShow = true;
          }
        },
        exportData() { // 导出
          let jsons = this.$refs.tables.selectionDatas;
          let param = {};
          if (jsons && jsons.length > 0) { // 优先按勾选内容导出
            param.ids = jsons.map(v => v.id);
            param.type = 1;
          } else { // 存在搜索条件时则按搜索条件导出
            if (this.queryForm.defenseDate && this.queryForm.defenseDate.length > 0) {
                this.queryForm.defenseDateBegin = parseInt(moment(this.queryForm.defenseDate[0]).format('x'));
                this.queryForm.defenseDateEnd = parseInt(moment(this.queryForm.defenseDate[1]).format('x'));
            }
            let condition = {};
            if (this.queryForm.stuNoOrName) {
                condition = {stuNoOrName:this.queryForm.stuNoOrName.trim(),status: "PASS"};
            }else{
                condition = _.cloneDeep(this.queryForm);
                condition.stuNoOrName = '';
            }
            param.request = condition;
            param.type = 0;
          }
          lookExportTable(param);
        },
        opens(val) {
          this.pathKey = val.type;
        },
        open(val, row) {
          this.pathKey = val;
          this.selectRow = row;
        },
        onSubmit() { // 筛选
          if (this.queryForm.defenseDate && this.queryForm.defenseDate.length > 0) {
            this.queryForm.defenseDateBegin = parseInt(moment(this.queryForm.defenseDate[0]).format('x'));
            this.queryForm.defenseDateEnd = parseInt(moment(this.queryForm.defenseDate[1]).format('x'));
          }
          this.$refs.tables.pageNum = 1;
          //查询关键字和筛选条件独立
          let param = {};
          if (this.queryForm.stuNoOrName) {
              param = {stuNoOrName:this.queryForm.stuNoOrName.trim(),status: "PASS"};
          }else{
              param = _.cloneDeep(this.queryForm);
              param.stuNoOrName = '';
          }
          this.$refs.tables.search(param);
        },
        // 表格数据加载完成后调用
        tableLoadDone (data) {
          data.forEach(item => {
            item.hideState = item.examResult;
          });
        },
        reset() {  // 重置
          for (const key in this.queryForm) {
            if (key !== 'yearTerm' && key !== 'status') {
              this.queryForm[key] = '';
            }
          }
          this.queryForm.yearTerm = this.yearTerms;
          this.onSubmit();
        },
        search() { // 搜索
          this.queryForm.stuNoOrName = this.queryForm.stuNoOrName.trim();
          this.onSubmit();
        },
        loadDone() { // 页面加载时保存学期学年
          this.yearTerms = this.queryForm.yearTerm;
          this.onSubmit();
        },
        // 录入成绩按钮
        insertScoreFunc (row) {
          if(!row.expertSuggestion || row.expertSuggestion === ''){
            this.$message.warning(this.$t('preDefense.insertScoreInfo'));
            return;
          }
          if (!row.examResult || row.examResult === '') {
            this.$message.warning(this.$t('preDefense.examResultTips'));
            return;
          }
          this.$confirm(this.$t('preDefense.examResultSure'), this.$t('message.prompt'), { confirmButtonText: this.$t('message.confirm'), cancelButtonText: this.$t('message.cancel'), type: "warning" }).then(() => {
            let param = [{id: row.id, examResult: row.examResult }]
            lookInsertScore(param)
            .then(res => {
              if (res.code === 200) {
                row.hideState = true;
                this.$message({
                  type: "success",
                  message: this.$t('preDefense.examResultSuccess')
                });
                this.reset();
              }
            });
          }).catch(e => { });
        },
        //可用TeacherSelect通用组件替换
        selectUser(query) {
          if (!query) return
          const data = {
              condition: query,
              pageNum_: 1,
              pageSize_: 10
          }
          this.loading = true
          findTeacherInfoList(data)
              .then(res => {
                  this.loading = false
                  if (res.code == 200) {
                      this.users = this.transData(res.data.list)
                  } else throw res.code
              })
              .catch(error => {
                  this.loading = false
                  this.$message({
                      type: 'error',
                      message: '查询用户出错'
                  })
              })
        },
        transData(list) {
          return list.map((item, index, array) => {
            return {
                label: item.name + '(' + item.code + ')',
                value: item.code
            }
          })
        },
        backFunc () {
          this.pathKey = 'main';
          this.reset();
        },
        exportWord(row) {
            let title = "预答辩结果表.doc"
            //导出申请表或结果表
            applyExportDoc(row.id,title);
        },
    }
};
</script>

<style scoped lang="scss">
.con {
    &_searchRight {
        margin-left: 10px;
    }
}
.condition-title {
  color: #2b3b4e;
  font-size: 18px;
  line-height: 24px;
  font-weight: bold;
}
</style>

